package com.yc.game.service.impl;

import com.yc.game.pojo.Cart;
import com.yc.game.pojo.Order;
import com.yc.game.service.OrderService;
import com.yc.game.dao.CartMapper;
import com.yc.game.dao.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;

    /**
     * 添加商品到订单
     */
    @Override
    public int addOrder(Order order, String email) {
        List<Cart> carts = cartMapper.getByEmail(email);
        // 生成订单
        long orderNum = orderNum();
        // 循环写入订单表
        for (Cart cart : carts) {
            Order newOrder = new Order();
            newOrder.setOrderNum(String.valueOf(orderNum));
            newOrder.setAddressDetail(order.getAddressDetail());
            newOrder.setCode(order.getCode());
            newOrder.setCompanyAddress(order.getCompanyAddress());
            newOrder.setCompanyName(order.getCompanyName());
            newOrder.setEmail(email);
            newOrder.setProductId(cart.getId());
            newOrder.setProductName(cart.getFoodName());
            newOrder.setSinglePrice(cart.getPrice());
            newOrder.setTotalPrice(cart.getTotalPrice());
            newOrder.setQuantity(cart.getQuantity());
            newOrder.setImgUrl(cart.getFoodImg());
            newOrder.setOrderStatus(1);
            newOrder.setPayment(order.getTotalPrice());
            newOrder.setPayTime(new Date());
            newOrder.setTotalPrice(cart.getTotalPrice());
            newOrder.setPayType(1);
            newOrder.setShi(order.getShi());
            newOrder.setSheng(order.getSheng());
            newOrder.setReciver(order.getReciver());
            newOrder.setQuantity(order.getQuantity());
            newOrder.setPhone(order.getPhone());
            newOrder.setQu(order.getQu());
            return orderMapper.insertSelective(newOrder);
        }
        return 0;
    }


    // 生成订单号
    private long orderNum() {
        long orderNum = System.currentTimeMillis() + new Random().nextInt(10);
        return orderNum;
    }
}
